//
//  LKDirectShopViewController.m
//  Mideleague_Agent
//
//  Created by Zhiwang on 2020/9/14.
//  Copyright © 2020 Zhiwang. All rights reserved.
//

#import "LKDirectShopViewController.h"
#import "LKSearchBar.h"
#import "LKMyShopListCell.h"
#import "LKMyShopDetailViewController.h"
#import "LKMyShopListDetailModel.h"
#import "LKSearchResultViewController.h"
#import "LKTreeBenefitViewController.h"
@interface LKDirectShopViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,MYTreeTableViewControllerDelegate>

@property(nonatomic,strong)LKSearchBar *mySearchBar;
@property(nonatomic,strong)LKBaseTableview *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,copy)NSString * timeType;
@property(nonatomic,copy)NSString * priceType;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,strong)NSMutableDictionary *paramDic;
@property(nonatomic,copy)NSString *shopType;
@property(nonatomic,strong)NSDictionary *currentSelectedDic;

@property (nonatomic,retain) UISearchController *searchController;
@property(nonatomic,strong)LKSearchResultViewController *searchResultVc;
@property(nonatomic,strong)UIView *searchBarView;
@property(nonatomic,strong)UIView *editingView;
@property(nonatomic,strong)LKBaseButton *rightBtn;
@property(nonatomic,strong)NSMutableArray *selecteArray;
@property(nonatomic,strong)WMZDropDownMenu *menu;
@end

@implementation LKDirectShopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"直属商户";
    [self setNavgationRightBtn];
    self.page = 0;
    self.timeType = @"0";
    self.shopType = @"1";
    self.priceType = @"1";
    self.paramDic = [[NSMutableDictionary alloc] initWithDictionary:@{@"sort_mode":self.priceType,@"page":@(self.page)}];;
    [self getShopListDataWithParam:self.paramDic];
    [self setupSearchView];
    [self setUpSearchViewController];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headerReloadDataNotice) name:@"handMerchantOverNotice" object:nil];
    // Do any additional setup after loading the view.
}
-(void)headerReloadDataNotice{
    [SVProgressHUD showInfoWithStatus:@"交接完成"];
    [self headerReloadData];
}
-(void)setNavgationRightBtn{
    WS(weakSelf)
    if (![[LKUserInforTool account].agent_role_name isEqual:@"省总"]) {
        return;
    }
    _rightBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"商户交接" titleColor:COLOR_HEX(0xF86747) layercorne:13 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 12] backgroudColor:[UIColor clearColor] AndActionBlock:^(UIButton * _Nonnull btn) {
        [weakSelf.view addSubview:self.editingView];
        btn.selected = !btn.selected;
        if (btn.selected) {
            [weakSelf.tableView setEditing:YES animated:YES];
            [weakSelf showEitingView:YES];
        }else{
            [weakSelf.tableView setEditing:NO animated:YES];
            [weakSelf showEitingView:NO];
        }

    }];
    _rightBtn.layer.borderColor = COLOR_HEX(0xF86747).CGColor;
    _rightBtn.layer.borderWidth = 1;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
}
//设置搜索框
-(void)setupSearchView{
    self.searchBarView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, 40)];
    _searchBarView.backgroundColor = viewDefualtColor;
        [self.view addSubview:_searchBarView];
    WMZDropMenuParam *param =
    MenuParam()
    .wMainRadiusSet(0)
    .wCollectionViewCellSelectTitleColorSet(yellowDefaultColor)
    .wCollectionViewSectionRecycleCountSet(3)
    .wMaxHeightScaleSet(0.6)
    .wBorderShowSet(NO)
    .wCellSelectShowCheckSet(NO)
    .wMenuTitleEqualCountSet(2);
    self.menu = [[WMZDropDownMenu alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 40, WIDTH, 40) withParam:param];
    self.menu.delegate = self;
    [self.view addSubview:self.menu];
    self.tableView = [LKBaseTableview setTableviewWithFrame:CGRectZero style:UITableViewStyleGrouped registercellClasss:@[@"LKMyShopListCell"]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.emptyDataSetSource = self;
    _tableView.emptyDataSetDelegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:_tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.menu.mas_bottom).offset(1);
        make.bottom.equalTo(self.view).offset(0);
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerReloadData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerReloadData)];
}

/// 上拉刷新
-(void)headerReloadData{
    self.page = 0;
    [self.paramDic setObject:@(self.page) forKey:@"page"];
    [self getShopListDataWithParam:self.paramDic];
    UIButton *selecteBtn = (UIButton *)[self.view viewWithTag:10001];
    selecteBtn.selected = NO;
}

/// 下拉加载更多
-(void)footerReloadData{
    self.page++;
    [self.paramDic setObject:@(self.page) forKey:@"page"];
    [self getShopListDataWithParam:self.paramDic];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LKMyShopListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMyShopListCell"];
    cell.myShoplistModel = self.dataArray[indexPath.section];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 135.0f;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] init];
    return headerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.000000001f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] init];
    return footerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1.0f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (tableView.isEditing)
    {
        if ([self.selecteArray containsObject:indexPath]) {
            [self.selecteArray removeObject:indexPath];
        }else{
            [self.selecteArray addObject:indexPath];
        }
        return;
    }else{
        LKMyShopDetailViewController *detailVc = [[LKMyShopDetailViewController alloc] init];
        detailVc.listModel = self.dataArray[indexPath.section];
        [self.navigationController pushViewController:detailVc animated:YES];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleNone) {
        
    }
}
- (UIView *)findViewWithClassName:(NSString *)className inView:(UIView *)view{
    Class specificView = NSClassFromString(className);
    if ([view isKindOfClass:specificView]) {
        return view;
    }
    if (view.subviews.count > 0) {
        for (UIView *subView in view.subviews) {
            UIView *targetView = [self findViewWithClassName:className inView:subView];
            if (targetView != nil) {
                return targetView;
            }
        }
    }
    return nil;
}
#pragma mark -Menu的代理设置

- (NSArray*)titleArrInMenu:(WMZDropDownMenu *)menu{
    return @[
 @{@"name":@"全部日期",@"normalImage":@"menu_dowm",@"selectImage":@"menu_up"},
         @{@"name":@"金额高到低",@"normalImage":@"menu_dowm",@"selectImage":@"menu_up"}
    ];
}


- (NSInteger)menu:(WMZDropDownMenu *)menu numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSArray *)menu:(WMZDropDownMenu *)menu dataForRowAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
    if (dropIndexPath.section == 0){
          return @[@"全部时间",@"昨天",@"本周",@"本月"];
      }else if (dropIndexPath.section == 1){
          return @[@"交易额由高到低",@"交易额由低到高",@"开户时间最新",@"开户时间最久"];
      }
      return @[];
}


- (NSInteger)menu:(WMZDropDownMenu *)menu countForRowAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return 2;
}
/*
*是否关联 其他标题 即选中其他标题 此标题会不会取消选中状态 default YES
*/
- (BOOL)menu:(WMZDropDownMenu *)menu dropIndexPathConnectInSection:(NSInteger)section{
    return NO;
}
- (CGFloat)menu:(WMZDropDownMenu *)menu heightAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath AtIndexPath:(NSIndexPath *)indexpath{
    if (dropIndexPath.section == 0 || dropIndexPath.section == 1) {
        return 50;
    }
    return 35;
}

- (MenuUIStyle)menu:(WMZDropDownMenu *)menu uiStyleForRowIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return MenuUITableView;
}

- (MenuHideAnimalStyle)menu:(WMZDropDownMenu *)menu hideAnimalStyleForRowInSection:(NSInteger)section{
    return MenuHideAnimalTop;
}

- (MenuShowAnimalStyle)menu:(WMZDropDownMenu *)menu showAnimalStyleForRowInSection:(NSInteger)section{
      return MenuShowAnimalBottom;
}


- (UITableViewCell*)menu:(WMZDropDownMenu *)menu cellForUITableView:(WMZDropTableView *)tableView AtIndexPath:(NSIndexPath *)indexpath dataForIndexPath:(WMZDropTree *)model{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GanJiTableViewCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"GanJiTableViewCell"];
    }
    cell.textLabel.text = model.name;
    cell.textLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:13];
    cell.textLabel.textColor = model.isSelected?yellowDefaultColor:MenuColor(0x666666);
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    return cell;
}
- (BOOL)menu:(WMZDropDownMenu *)menu closeWithTapAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return YES;
}

-  (void)menu:(WMZDropDownMenu *)menu didSelectRowAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath dataIndexPath:(NSIndexPath *)indexpath data:(WMZDropTree *)data{
    if (dropIndexPath.section == 0) {
        if (indexpath.row == 0) {
           self.timeType = [NSString stringWithFormat:@"%ld",(long)indexpath.row];
        }else{
           self.timeType = [NSString stringWithFormat:@"%ld",(long)indexpath.row + 1];
        }

        self.paramDic = [[NSMutableDictionary alloc] initWithDictionary:@{@"time_type":self.timeType,@"sort_mode":self.priceType,@"status":self.shopType,@"page":@(self.page)}];
        [self getShopListDataWithParam:self.paramDic];
        NSLog(@"点击了%ld",indexpath.row);
    }
    if (dropIndexPath.section == 1) {
        self.priceType = [NSString stringWithFormat:@"%ld",(long)indexpath.row + 1];
        self.paramDic = [[NSMutableDictionary alloc] initWithDictionary:@{@"time_type":self.timeType,@"sort_mode":self.priceType,@"status":self.shopType,@"page":@(self.page)}];
        [self getShopListDataWithParam:self.paramDic];
    }
}

/// 获取商户列表数据
-(void)getShopListDataWithParam:(NSDictionary *)param{
//    NSDictionary *param = @{@"time_type":self.timeType,@"sort_mode":self.priceType,@"word":words,@"page":@(self.page)};
//    NSDictionary *param = @{@"is_search":@(YES),@"word":words,@"page":@(self.page)};
    [SVProgressHUD show];
    [self.paramDic setObject:self.uid forKey:@"directmer_uid"];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyShopListUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {

        if ([responseObject[@"code"] isEqual:@"success"]) {
            [SVProgressHUD dismiss];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            if (self.page == 0) {
                [self.dataArray removeAllObjects];
            }
            NSArray *datasArray = responseObject[@"data"];
            if (datasArray.count < 15) {
                for (NSDictionary *dic in datasArray) {
                    LKMyShoplistModel *model = [LKMyShoplistModel modelWithDictionary:dic];
                    [self.dataArray addObject:model];
                }
                self.tableView.mj_footer.hidden = YES;
            }else{
                for (NSDictionary *dic in datasArray) {
                    LKMyShoplistModel *model = [LKMyShoplistModel modelWithDictionary:dic];
                    [self.dataArray addObject:model];
                }
            }
            [self.tableView reloadData];
        }else{
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        }
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
-(NSMutableArray *)selecteArray{
    if (!_selecteArray) {
        _selecteArray = [[NSMutableArray alloc] init];
    }
    return _selecteArray;
}
/// 设置搜索控制器
-(void)setUpSearchViewController{
        //创建UISearchController
        self.searchResultVc = [[LKSearchResultViewController alloc] init];
        UINavigationController *navSearchVc = [[UINavigationController alloc] initWithRootViewController:self.searchResultVc];
        self.searchController = [[UISearchController alloc]initWithSearchResultsController:navSearchVc];
        //设置代理
        self.searchController.delegate= self.searchResultVc;
        self.searchController.searchResultsUpdater = self.searchResultVc;
        //包着搜索框外层的颜色
        self.searchController.searchBar.barTintColor = viewDefualtColor;
    self.searchController.searchBar.backgroundColor = viewDefualtColor;
        //提醒字眼
        self.searchController.searchBar.placeholder= @"请输入商户名称搜索";
        //设置UISearchController的显示属性，以下3个属性默认为YES
        //搜索时，背景变暗色
        self.searchController.dimsBackgroundDuringPresentation = YES;
        //搜索时，背景变模糊
        self.searchController.obscuresBackgroundDuringPresentation = YES;
        
        //点击搜索的时候,是否隐藏导航栏
        self.searchController.hidesNavigationBarDuringPresentation = YES;
    [self.searchController.searchBar sizeToFit];
        //位置
//    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 40.0);
        self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 40);
    self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    self.searchController.view.backgroundColor = [UIColor whiteColor];
    [self.searchBarView addSubview:self.searchController.searchBar];
    #warning 如果进入预编辑状态,searchBar消失(UISearchController套到TabBarController可能会出现这个情况),请添加下边这句话
    self.definesPresentationContext=YES;

}




- (void)showEitingView:(BOOL)isShow
{
    [UIView animateWithDuration:0.3 animations:^{
        self.editingView.frame = CGRectMake(0, isShow ? HEIGHT - 45 : HEIGHT, WIDTH, 50);
    }];
    if (isShow) {
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.top.equalTo(self.menu.mas_bottom).offset(1);
            make.bottom.equalTo(self.editingView.mas_top).offset(0);
        }];
    }else{
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.top.equalTo(self.menu.mas_bottom).offset(1);
            make.bottom.equalTo(self.view).offset(0);
        }];
    }
}
- (UIView *)editingView
{
    if (!_editingView) {
        _editingView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT, WIDTH, 50)];
        _editingView.backgroundColor = [UIColor whiteColor];
        UIButton * selectebutton = [UIButton buttonWithType:UIButtonTypeCustom];
        [selectebutton setTitleColor:COLOR_HEX(0x333333) forState:UIControlStateNormal];
        selectebutton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        [selectebutton setTitle:@" 全选" forState:UIControlStateNormal];
        [selectebutton setTitle:@" 全不选" forState:UIControlStateSelected];
        [selectebutton addTarget:self action:@selector(viewbuttonClick:) forControlEvents:UIControlEventTouchUpInside];
        selectebutton.frame = CGRectMake(20, 10, 100, 30);
        [selectebutton setImage:[UIImage imageNamed:@"weixuanzhong_customer"] forState:UIControlStateNormal];
        [selectebutton setImage:[UIImage imageNamed:@"xuanzhong_customer"] forState:UIControlStateSelected];
        [_editingView addSubview:selectebutton];
        UIButton *handlebutton = [UIButton buttonWithType:UIButtonTypeCustom];
        handlebutton.backgroundColor = [UIColor redColor];
        [handlebutton setTitle:@"交接" forState:UIControlStateNormal];
        handlebutton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        [handlebutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        handlebutton.layer.cornerRadius = 15;
        handlebutton.layer.masksToBounds = YES;
        handlebutton.backgroundColor = yellowDefaultColor;
        [handlebutton addTarget:self action:@selector(viewbuttonClick:) forControlEvents:UIControlEventTouchUpInside];
        handlebutton.frame = CGRectMake(WIDTH - 90, 10, 70, 30);
        [_editingView addSubview:handlebutton];
        UIButton *cancelbutton = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelbutton.backgroundColor = COLOR_HEX(0x999999);
        [cancelbutton setTitle:@"取消" forState:UIControlStateNormal];
        cancelbutton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        [cancelbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cancelbutton addTarget:self action:@selector(viewbuttonClick:) forControlEvents:UIControlEventTouchUpInside];
        cancelbutton.frame = CGRectMake(WIDTH - 170, 10, 70, 30);
        cancelbutton.layer.cornerRadius = 15;
        cancelbutton.layer.masksToBounds = YES;
        selectebutton.tag = 10001;
        cancelbutton.tag = 10002;
        handlebutton.tag = 10003;
        [_editingView addSubview:cancelbutton];
    }
    return _editingView;
}
-(void)viewbuttonClick:(UIButton *)sender{
    if (sender.tag == 10001) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:idx] animated:YES scrollPosition:UITableViewScrollPositionNone];
            }];
        }else{
            [[self.tableView indexPathsForSelectedRows] enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                 [self.tableView deselectRowAtIndexPath:obj animated:NO];
             }];
        }
    }else if (sender.tag == 10002){
        self.rightBtn.selected  = NO;
        [self.tableView setEditing:NO animated:YES];
        [self showEitingView:NO];
    }else{
        NSMutableArray *selectArray = [[NSMutableArray alloc] init];
        for (LKMyShoplistModel *model in self.dataArray) {
            if (model.selected) {
               [selectArray addObject:model];
            }
        }
        if (selectArray.count == 0) {
            [SVProgressHUD showInfoWithStatus:@"请选择要交接的商户"];
            return;
        }
        LKTreeBenefitViewController *vc = [[LKTreeBenefitViewController alloc] init];
        vc.isShowCheck = YES;
        vc.delegate = self;
        vc.isSingleCheck = YES;
        vc.isCancelSingleCheck = YES;
        vc.isShowTimeChoose = NO;
        vc.handlerId = self.uid;
        vc.handleShopsArray = selectArray;
        [self.navigationController pushViewController:vc animated:YES];
    }

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
